var {User}=require("./mongos");
function insertUser(data){
   return new Promise(function(resolve,reject){
        new User(data).save({},function(err,data){
            resolve(data);
        })
   })
}

function deleteUser(valueObj){
  return new Promise(function(resolve,reject){
    User.deleteOne(valueObj,function(err,data){
      resolve(data);
    })
  })
}
//conditon 条件 valueObj修改的参数
function updateUserById(id,valueObj){
    return new Promise(function(resolve,reject){
      User.findByIdAndUpdate(id,{$set:valueObj},function(err,data){
            resolve(data);
        })
    })
}
//查找所有下级用户
function showListUser(condition){
   return new Promise(function(resolve,reject){
    User.find(condition,function(err,data){
            resolve(data);
        })
   })
}
function Select(obj){
    return new Promise(function(resolve,reject){
      User.findOne(obj,function(err,data){
            resolve(data);
        })
   })
}
function SelectByid(_id){
  return new Promise(function(resolve,reject){
    User.findById(_id,function(err,data){
          resolve(data);
      })
 })
}
function getCondition(condition) {
    var arr = condition.split("&&");
    var map = {
      "<": "$lt",
      ">": "$gt",
      "<=": "$lte",
      ">=": "$gte",
      "==": ""
    }
    var obj = {};
    var o = {};
    var symbol
    for (var i = 0; i < arr.length; i++) {
      var arr1 = arr[i].match(/([a-z]+|\_[a-z]+)(\<|\>|\<\=|\>\=|\=\=|\!\=)(.+)/i).slice(1);
      if (!o[arr1[0]]) o[arr1[0]] = [];
      o[arr1[0]].push([arr1[1], arr1[2]]);
    }
    for (var key in o) {
      if (o[key].length > 1) {
        obj[key] = {}
        for (var j = 0; j < o[key].length; j++) {
          symbol = map[o[key][j][0]];
          obj[key][symbol] = isNaN(o[key][j][1]) ? o[key][j][1] : Number(o[key][j][1]);
        }
      } else {
        if (o[key][0][0] === "==") {
          obj[key] = o[key][0][1];
        } else {
          obj[key] = {}
          symbol = map[o[key][0][0]];
          obj[key][symbol] = isNaN(o[key][0][1]) ? o[key][0][1] : Number(o[key][0][1]);
        }
      }
  
    }
    return obj;
  }
module.exports = {
  insertUser,
  deleteUser,
  showListUser,
  updateUserById,
  Select,
  SelectByid,
}